package com.geping.etl.common.security.pwd.impl;

import com.geping.etl.common.entity.Sys_UserAndOrgDepartment;
import com.geping.etl.common.security.pwd.PwdPolicyConstant;
import com.geping.etl.common.security.pwd.PwdPolicyService;
import com.geping.etl.common.security.pwd.PwdPolicyServiceDispatcher;
import com.geping.etl.common.security.pwd.bo.PwdPolicyBo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Service
public class BaomaPwdPolicyServiceImpl extends PwdPolicyServiceDispatcher implements PwdPolicyService {

    @Resource
    private HttpSession session;


    /**
     * 特殊字符
     */
    private static  String  SPECIAL_CHARACTERS="&*:#_-";

    /**
     * 宝马密码规则之一
     */
    private static   String pattern="(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[&*:.!#_-])[\\da-zA-Z"+SPECIAL_CHARACTERS+"]{15,30}";

    /**
     * 初始化密码策略
     */
    private PwdPolicyBo pwdPolicyBo=new PwdPolicyBo("15到30个字符之间<br>(a-z, A-Z)的字母、数字或以下字符之一的组合:"+SPECIAL_CHARACTERS+"<br>不能包含用户id和名称");



    @Override
    public boolean validate(String pwd) {
        if(pwd.length()<15||pwd.length()>30){
            return false;
        }
        if(!containSingleSpecialCharacter(pwd)){
            return false;
        }
        Sys_UserAndOrgDepartment sys_user= (Sys_UserAndOrgDepartment) session.getAttribute("sys_User");
        Integer  userId=sys_user.getId();
        if(pwd.indexOf(String.valueOf(userId))>=0||pwd.indexOf(sys_user.getLoginid())>=0){
            return false;
        }
        return pwd.matches(pattern);
    }

    @Override
    public String getType() {
        return PwdPolicyConstant.BAOMA_POLICY;
    }

    @Override
    public PwdPolicyBo getPwdPolicy(){
        return pwdPolicyBo;
    }

    public static void main(String[] args) {
        BaomaPwdPolicyServiceImpl baomaPwdPolicyServiceImpl=new BaomaPwdPolicyServiceImpl();
        System.out.println(baomaPwdPolicyServiceImpl.validate("656TTTTTTTTTTTTTTTTr#"));
    }

    /**
     * 是否包含单个特殊字符
     * @return
     */
    public  boolean containSingleSpecialCharacter(String pwd){
        int sum=0;
        for(int i=0;i<pwd.length();i++){
            if(SPECIAL_CHARACTERS.indexOf(pwd.charAt(i))>=0){
                sum=sum+1;
            }
        }
        return sum==1;
    }
}